package com.cloxtec.scada.utils;


import java.security.MessageDigest;
import java.util.Random;
import java.util.UUID;


/**
 * Created by iot.cloxtec.com on 2017/11/7
 * UUID生成器
 */
public class UUIDGenerator {

	private static char[] chars1 = new char[] { 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', '0', '1', '2', '3', '4' };
	private static char[] chars2 = new char[] { 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', '5', '6', '7', '8', '9' };

	private final int instanceIdx;

	private static int instanceCount = 0;

	private static Object syncObj = new Object();

	private static long counter = 0;

	public UUIDGenerator() {
		instanceIdx = instanceCount++;
	}

	/**
	 * 获得一个32位的UUID
	 * 
	 * @return String UUID
	 */
	public static String getUUID32() {
		StringBuffer uuid32 = new StringBuffer(UUID.randomUUID().toString());
		// 去掉“-”符号
		uuid32.deleteCharAt(8).deleteCharAt(12).deleteCharAt(16).deleteCharAt(20);
		return uuid32.toString();
	}

	/**
	 * 获得一个16位的UUID
	 * 
	 * @return String UUID
	 */
	public static String getUUID16() {
		StringBuffer uuid32 = new StringBuffer(getUUID32());
		char[] tmp = new char[2];
		StringBuffer uuid16 = new StringBuffer("");
		int index = 0;
		int num1 = 0;
		int num2 = 0;
		for (int i = 0; i < 32; i += 2) {
			uuid32.getChars(i, i + 2, tmp, 0);
			num1 = Integer.parseInt(String.valueOf(tmp[0]), 16);
			num2 = Integer.parseInt(String.valueOf(tmp[1]), 16);
			index = num1 + num2;
			if (num1 > num2) {
				uuid16.append(chars1[index]);
			} else if (num1 < num2) {
				uuid16.append(chars2[index]);
			} else if (num1 == num2) {
				uuid16.append(chars1[num1]);
			}
		}
		return uuid16.toString();
	}
	public static int getNUMBER() {
		return (int)(Math.random()*100000000);
	}
	/**
	 * 生成9位的数字字符串,同一个手机号返回的串是固定的。 采用java.lang.String
	 * hashCode()算法，保证同一个字符串返回的结果相同。
	 * */
	public static final String toFixedIntStr(String str) {
		int h = 0;
		int off = 0;
		if (str == null || "".equals(str)) {
			str = "student";
		}
		char val[] = str.toCharArray();
		int len = val.length;
		for (int i = 0; i < len; i++) {
			h = 31 * h + val[off++];
		}
		return Math.abs(h) + "";
	}

	public static String genInvitationCode(int count) {
		StringBuffer sb = new StringBuffer();
		String str = "0123456789abcdefhijklmnopqrstuvwxyz";
		Random r = new Random();
		for (int i = 0; i < count; i++) {
			int num = r.nextInt(str.length());
			sb.append(str.charAt(num));
			str = str.replace((str.charAt(num) + ""), "");
		}
		return sb.toString().toUpperCase();
	}

	public String genTokenId(String deviceId, String carOwnerCode) {
		String tokenKey = getTokenKey(deviceId, carOwnerCode);

		byte b[] = tokenKey.getBytes();
		try {
			String encryptionAlgorithm = "SHA";
			MessageDigest messageDigest = MessageDigest.getInstance(encryptionAlgorithm);
			b = messageDigest.digest(b);

			StringBuffer stringbuffer = new StringBuffer(40);

			for (int l = 0; l < b.length; l++) {
				int k = b[l] + 128;
				int i = k / chars2.length;
				int j = k % chars2.length;
				stringbuffer.append(chars2[i]);
				stringbuffer.append(chars2[j]);
			}

			return stringbuffer.toString();

		} catch (Exception e) {
			e.printStackTrace();
		}

		return null;
	}

	private String getTokenKey(String deviceId, String carOwnerCode) {
		char SEPARATOR = '|';
		StringBuffer buf = new StringBuffer();

		buf.append(deviceId); // 根据设备编号

		buf.append(SEPARATOR);

		buf.append(carOwnerCode); // 根据用户编号

		buf.append(SEPARATOR);

		buf.append(String.valueOf(instanceIdx)); // 实例计数
		buf.append(SEPARATOR);

		long l;
		synchronized (syncObj) {
			l = ++counter;
		}

		buf.append(Long.toHexString(l)); // 计数器
		buf.append(SEPARATOR);

		buf.append(Long.toHexString(System.currentTimeMillis())); // 当前时间
		buf.append(SEPARATOR);

		return buf.toString();

	}


}
